import Access from '@/components/Access';
import type { ProColumns } from '@/components/Pro';
import { ProTable } from '@/components/Pro';
import { otaConfigControllerStationPage as tableList } from '@/services/ess/otaConfig';
import { fetchDictInfo } from '@/utils';
import { useModel } from '@@/exports';
import { CascaderProps, GetProp, Space } from 'antd';
import React, { useEffect, useState } from 'react';
import { Link, useIntl } from 'umi';
import Styles from '../index.less';
type DefaultOptionType = GetProp<CascaderProps, 'options'>[number];
const filter = (inputValue: string, path: DefaultOptionType[]) => {
  return path.some((option) => {
    const label = option.label as string;
    return label.toLowerCase().includes(inputValue.toLowerCase()) && path.length === 2;
  });
};

const UpgradeManagement: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [tenantOptions, setTenantOptions] = useState([]);
  const [deviceOptions, setDeviceOptions] = useState([]);
  const [disableSearch, setDisableSearch] = useState<boolean>(false); // 控制查询按钮禁用状态
  const intl = useIntl();
  const isEnglish = intl.locale === 'en-US';
  const tableColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.SN' }),
      dataIndex: 'NO',
      key: 'NO',
      valueType: 'index',
      width: 60,
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.siteConfigurationManagement.selectPlant',
      }),
      dataIndex: 'id',
      key: 'id',
      valueType: 'cascader',
      hideInTable: true,
      fieldProps: {
        options: tenantOptions,
        changeOnSelect: true,
        showSearch: { filter }, // 启用搜索功能
        onChange: (value, selectedOptions) => {
          if (selectedOptions && selectedOptions.length < 2) {
            setDisableSearch(true);
          } else {
            setDisableSearch(false);
          }
        },
      },
      search: {
        transform: (value) => {
          return {
            id: value?.at(-1),
          };
        },
      },
    },

    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.siteConfigurationManagement.plantName',
      }),
      dataIndex: 'stationName',
      order: 4,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.siteConfigurationManagement.updateTime',
      }),
      dataIndex: 'configUpdateTime',
      key: 'configUpdateTime',
      width: 150,
      colSize: 2,
      // initialValue: [dayjs().subtract(6, 'day'), dayjs()],
      valueType: 'dateTimeRange',
      render: (_, record) => {
        return <span>{record.configUpdateTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            configStartTime: value?.[0],
            configEndTime: value?.[1],
          };
        },
      },
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.siteConfigurationManagement.operation',
      }),
      hideInSearch: true,
      dataIndex: 'operation',
      key: 'operation',
      render: (_, record) => {
        const handleLinkClick = () => {
          const SiteConfigurationParams = {
            configUpdateTime: record?.configUpdateTime,
            otaStatus: record?.otaStatus,
            stationName: record?.stationName,
            id: record?.id,
          };
          sessionStorage.setItem(
            'SiteConfigurationParams',
            JSON.stringify(SiteConfigurationParams),
          );
        };

        return (
          <Access perm={'remote:siteconfig'}>
            <Space>
              <Access perm={'remote:siteupdate'} key={'link'}>
                <Link
                  to={`/remoteUpgrade/SiteConfigurationManagement/update`}
                  onClick={handleLinkClick}
                  key={'link'}
                >
                  <span>
                    {intl.formatMessage({
                      id: 'remoteUpgradeMangment.siteConfigurationManagement.update',
                    })}
                  </span>
                </Link>
              </Access>
              <Access perm={'remote:siteems'} key={'link2'}>
                <Link
                  to={`/remoteUpgrade/SiteConfigurationManagement/ems?stationId=${record?.id}`}
                  onClick={handleLinkClick}
                  key={'link2'}
                >
                  <span>
                    {intl.formatMessage({
                      id: 'remoteUpgradeMangment.siteConfigurationManagement.emsController',
                    })}
                  </span>
                </Link>
              </Access>
            </Space>
          </Access>
        );
      },
    },
  ];
  const getTenantOptions = (options: any) => {
    const treeData = [];

    function getTreeChildren(stationOptions: any[]) {
      return stationOptions.map((item) => {
        return {
          label: item.stationName,
          value: item.id,
        };
      });
    }

    options.forEach((item) => {
      treeData.push({
        value: item.tenantName,
        label: item.tenantName,
        children: getTreeChildren(item.stationInfos),
      });
    });
    setTenantOptions(treeData);
  };

  useEffect(() => {
    getTenantOptions(initialState?.tenants);
    fetchDictInfo(100009).then((res) => {
      setDeviceOptions(res);
      console.log(deviceOptions);
    });
  }, []);
  return (
    <>
      <ProTable
        headerTitle={
          <div className={`${isEnglish ? Styles.table_header_title : ''}`}>
            {intl.formatMessage({
              id: 'remoteUpgradeMangment.siteConfigurationManagement.plantConfigurationManagement',
            })}
          </div>
        }
        rowKey={'pageIndex'}
        columns={tableColumns}
        request={async (values) => {
          try {
            if (!disableSearch) {
              const params = {
                id: '',
                ...values,
              };
              let reslut = await tableList(params);
              console.log('reslut----------', reslut);
              return reslut;
            }
          } catch (error) {}
        }}
      ></ProTable>
    </>
  );
};

export default UpgradeManagement;
